<?php

namespace App\Http\Controllers;

use App\Models\ActivityType;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use \DB;
use App\Http\Requests\ActivityTypeRequest;

class ActivityTypeController extends CommonController
{
    /**
     *获取活动类型列表
     *
     */
    public function getIndex()
    {
        $lists = DB::table('activity_type')->orderBy('sort', 'asc')->paginate(10);

        return view('activitytype.index')->with('lists', $lists)->with("actions", $this->actions);
    }

    /**
     * 获取编辑界面
     *
     */
    public function getEdit(Request $request)
    {
        $id = $request->input('id');
        $info = DB::table('activity_type')
            ->where('activity_type.id', '=', $id)
            ->first();

        return view('activitytype.edit')->with('info', $info);
    }

    /**
     * 编辑一个活动类型
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function postEdit(ActivityTypeRequest $request)
    {
        $data = $request->input();
        $nameExist = ActivityType::where('name', trim($data['name']))->first();
        if (is_object($nameExist) && $nameExist->id != $data['id']) {
            return AjaxCallbackMessage('编辑失败，该类型名称已经存在', false);
        }

        $codeExist = ActivityType::where('code', trim($data['code']))->first();

        if (is_object($codeExist) && $codeExist->id != $data['id']) {
            return AjaxCallbackMessage('编辑失败，该类型code已经存在', false);
        }

        unset($data['formType'], $data['_token']);

        ActivityType::where('id', '=', $data['id'])->update($data);

        return AjaxCallbackMessage('编辑成功', true, url('activitytype/index'));
    }

    /**
     *显示活动类型创建的页面
     *
     * @return View
     */
    public function getCreate()
    {
        return view('activitytype.create');
    }

    /**
     * 创建一个活动类型
     *
     */
    public function postCreate(ActivityTypeRequest $request)
    {
        $data = $request->input();
        unset($data['formType'], $data['_token']);
        $result = DB::table('activity_type')->insertGetId($data);

        if ($result) {
            return AjaxCallbackMessage('创建成功', true, url('activitytype/index'));
        } else {
            return AjaxCallbackMessage('创建失败', false);
        }
    }
}
